package il.ac.tau.cg.ex3.math.intersectors;

import il.ac.tau.cg.ex3.math.Point;
import il.ac.tau.cg.ex3.math.Vector;
import il.ac.tau.cg.ex3.math.shapes.Intersectable;

import java.util.Collection;
import java.util.SortedSet;

public abstract class Intersector
{
	private static final double INT_EPSILON	= 1e-7;
	
	public abstract IntersectionResult intersect(Point origin, Vector direction);
	
	protected IntersectionResult intersectCollection(Point origin, Vector direction,
			Collection<? extends Intersectable> intersectables)
	{
		Intersectable closestIntersectable = null;
		double closestParam = Double.POSITIVE_INFINITY;
		
		for (Intersectable intersectable : intersectables)
		{
			SortedSet<Double> ints = intersectable.intersect(origin, direction);
			
			if (!ints.isEmpty())
			{
				double param = ints.first();
				
				if ((Math.abs(param) > INT_EPSILON) && (param < closestParam))
				{
					closestIntersectable = intersectable;
					closestParam = param;
				}
			}
		}
		
		if (closestIntersectable == null)
		{
			return null;
		}
		
		return new IntersectionResult(closestIntersectable, closestParam);
	}
}
